<%--
  -	Date: 2012-05-25
  -
  - Copyright (C) 2012 Jawa Software. All rights reserved.
  - 
  - 创建新用户页面。
--%>
<%@ page language="java" pageEncoding="utf-8"%>
<%@ taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%>
<%@ page import="org.jawa.admin.util.ParamUtils,org.jawa.core.util.JawaGlobals,org.jawa.core.JawaServer,org.jawa.user.User,org.jawa.user.UserManager,org.jawa.branch.Branch,org.jawa.branch.BranchManager,org.jawa.core.database.SequenceManager,org.jawa.core.util.JawaConstants"
%>
<%@ page import="java.util.Collection,java.util.List,java.util.ArrayList,java.util.Map,java.util.HashMap,java.net.URLEncoder"
%>
<%@ page import="org.apache.commons.lang.StringUtils"%>
<jsp:useBean id="webManager" class="org.jawa.admin.util.WebManager"  />
<% 
    webManager.init(request, response, session, application, out);
	String path = request.getContextPath();
%>

<%
	Map<String,String> errors = new HashMap<String,String>();
	boolean success;
	
	boolean edit = request.getParameter("edit") != null;
	boolean create = request.getParameter("create") != null;
	boolean update = request.getParameter("update") != null;
	boolean delete = request.getParameter("delete") != null;
	
	Long userId = ParamUtils.getLongParameter(request,"userId",-1L);
	User user = null;
	if(edit){
		try{
			user = UserManager.getInstance().getUser(userId);
		}catch(Exception ex){
			//忽略
		}
	}
	if(null==user){
		user = new User();
	}
	
	if (delete)
	{
		UserManager.getInstance().deleteUser(userId);
		success = true;
		response.sendRedirect("index.jsp?delete=true&success=true");
        return;
	}
	
	
	//创建用户
	if (create)
	{
		String brId = ParamUtils.getParameter(request,"brId");
		String loginNo = ParamUtils.getParameter(request,"loginNo");
		String userName = ParamUtils.getParameter(request,"userName");
		String userType = ParamUtils.getParameter(request,"userType");
		String userStatus = ParamUtils.getParameter(request,"userStatus");

		String userSex = ParamUtils.getParameter(request,"userSex");
		String userPhone = ParamUtils.getParameter(request,"userPhone");
		String userEmail = ParamUtils.getParameter(request,"userEmail");
		String userPicture = ParamUtils.getParameter(request,"userPicture");
		
		if(StringUtils.isEmpty(brId)){
			errors.put("brId","");
		}
		if(StringUtils.isEmpty(loginNo)){
			errors.put("loginNo","");
		}
		if(StringUtils.isEmpty(userName)){
			errors.put("userName","");
		}
		if(StringUtils.isEmpty(userType)){
			errors.put("userType","");
		}
		if(StringUtils.isEmpty(userStatus)){
			errors.put("userStatus","");
		}
		
		if(errors.isEmpty()){
			user = new User();
			user.setBrId(Long.valueOf(brId));
			user.setLoginNo(loginNo);
			user.setUserName(userName);
			user.setUserType(userType);
			user.setUserStatus(userStatus);
			user.setUserSex(userSex);
			user.setUserPhone(userPhone);
			user.setUserEmail(userEmail);
			user.setUserPicture(userPicture);
			try{
				Long nextUserId = SequenceManager.nextID(JawaConstants.DB_USER_SEQ);
				user.setUserId(nextUserId);
				user.setUserPassword(JawaConstants.USER_PASSWORD);
				UserManager.getInstance().createUser(user);
				success = true;
			}catch(Exception ex){
				success = false;
				errors.put("general","");
			}
			
			if(success){
	            response.sendRedirect("index.jsp?create=true&success=true");
	            return;
			}
			
		}
	}
	
	if (update)
	{
		String brId = ParamUtils.getParameter(request,"brId");
		String loginNo = ParamUtils.getParameter(request,"loginNo");
		String userName = ParamUtils.getParameter(request,"userName");
		String userType = ParamUtils.getParameter(request,"userType");
		String userStatus = ParamUtils.getParameter(request,"userStatus");

		String userSex = ParamUtils.getParameter(request,"userSex");
		String userPhone = ParamUtils.getParameter(request,"userPhone");
		String userEmail = ParamUtils.getParameter(request,"userEmail");
		String userPicture = ParamUtils.getParameter(request,"userPicture");
		
		if(StringUtils.isEmpty(brId)){
			errors.put("brId","");
		}
		if(StringUtils.isEmpty(loginNo)){
			errors.put("loginNo","");
		}
		if(StringUtils.isEmpty(userName)){
			errors.put("userName","");
		}
		if(StringUtils.isEmpty(userType)){
			errors.put("userType","");
		}
		if(StringUtils.isEmpty(userStatus)){
			errors.put("userStatus","");
		}
		
		if(errors.isEmpty()){
			try{
				UserManager.getInstance().updateUser(userId,brId,loginNo,userName,userType,userStatus,userSex,userPhone,userEmail,userPicture);
				success = true;
			}catch(Exception ex){
				success = false;
				errors.put("general","");
			}
			
			if(success){
	            response.sendRedirect("index.jsp?update=true&success=true");
	            return;
			}
			
		}
	}

%>
<!DOCTYPE html>
<html lang="en">
	<head>
		<title>创建新用户</title>
		<meta name="pageID" content="1202" />
		<link rel="stylesheet"  href="<%= path %>/styles/uploadify.css">
		<link rel="stylesheet"  href="<%= path %>/styles/ztree/ztree.css">
		<style type="text/css">
		    .uploadify-button {
		        background-color: transparent;
		        border: none;
		        padding: 0;
		    }
		    .uploadify:hover .uploadify-button {
		        background-color: transparent;
		    }
		</style>
	</head>
	<body>
		<div class="row-fluid">

			<ul class="breadcrumb">
				<li>
					您现在的位置:
				</li>
				<li>
					<a href="<%=path%>/admin/index.jsp">系统管理</a>
				</li>
				<li>
					<span class="divider">/</span>
				</li>
				<li>
					<a href="<%=path%>/admin/user/index.jsp">用户管理</a>
				</li>
				<li>
					<span class="divider">/</span>
				</li>
				<li class="active">
					创建新用户
				</li>
			</ul>
			<%
				if(errors.get("general")!=null)
				{
			%>		
				  <div class="alert alert-error fade in">
				    <a class="close" data-dismiss="alert" href="#">×</a>
					<strong>创建用户时发生错误,可能是用户编号已存在.</strong>
				  </div>			
			<%	
				}
			%>
			<form id="userForm" action="user-form.jsp" method="post" class="form-horizontal well">
			    <%
			    	if(edit){
			    %>
			    	<input type="hidden" name="userId" value="<%=user.getUserId() %>">
			    <%		
			    	}
			    %>
				<fieldset>
					<legend>
						创建用户
					</legend>
					<div class="row-fluid">
						<div class="span8">
							<div class="control-group">
								<label class="control-label">
									用户机构:
								</label>
								<div class="controls">
								    <%
								    	Branch userBranch = user.getBranch();
								    	String brName = "";
								    	if(null!=userBranch){
								    		brName = userBranch.getBrName();
								    	}
								    %>
									<input type="hidden" id="brId" name="brId" value="<%=user.getBrId() %>" />
									<input type="text" id="brName" name="brName" value="<%=brName %>" maxlength="15" class="" readonly="readonly" onclick="showMenu();" style="cursor: pointer;" />
									<%
										if (errors.get("brId") != null) {
									%>
									<span class="help-inline">请选择正确的机构</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户编号:
								</label>
								<div class="controls">
									<input type="text" name="loginNo" value="<%=StringUtils.trimToEmpty(user.getLoginNo()) %>"  maxlength="15"  class="" />
									<%
										if (errors.get("loginNo") != null) {
									%>
									<span class="help-inline">请输入用户编号</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户姓名:
								</label>
								<div class="controls">
									<input type="text" name="userName" value="<%=StringUtils.trimToEmpty(user.getUserName()) %>" maxlength="15"  class="" />
									<%
										if (errors.get("userName") != null) {
									%>
									<span class="help-inline">请输入用户姓名</span>
									<%
										}
									%>									
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户类型:
								</label>
								<div class="controls">
									<select id="userType" name="userType">
										<option value="0" <%=StringUtils.equals(user.getUserType(),"0")?"selected=\"selected\"":"" %> >
											用户
										</option>
										<option value="1" <%=StringUtils.equals(user.getUserType(),"1")?"selected=\"selected\"":"" %>>
											管理人员
										</option>
									</select>
									<%
										if (errors.get("userType") != null) {
									%>
									<span class="help-inline">请选择用户类型</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户状态:
								</label>
								<div class="controls">
									<select id="userStatus" name="userStatus" >
										<option value="0" <%=StringUtils.equals(user.getUserStatus(),"0")?"selected=\"selected\"":"" %>>
											正常
										</option>
										<option value="1" <%=StringUtils.equals(user.getUserStatus(),"1")?"selected=\"selected\"":"" %>>
											失效
										</option>
									</select>
									<%
										if (errors.get("userStatus") != null) {
									%>
									<span class="help-inline">请选择用户状态</span>
									<%
										}
									%>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									用户性别:
								</label>
								<div class="controls">
									<select id="userSex" name="userSex" >
										<option value="0" <%=StringUtils.equals(user.getUserSex(),"0")?"selected=\"selected\"":"" %>>
											男
										</option>
										<option value="1" <%=StringUtils.equals(user.getUserSex(),"1")?"selected=\"selected\"":"" %>>
											女
										</option>
									</select>
									<span class="help-inline"></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									联系电话:
								</label>
								<div class="controls">
									<input type="text" name="userPhone" value="<%=StringUtils.trimToEmpty(user.getUserPhone()) %>" maxlength="15"  class="" />
									<span class="help-inline"></span>
								</div>
							</div>
							<div class="control-group">
								<label class="control-label">
									电子邮件:
								</label>
								<div class="controls">
									<input  type="text" name="userEmail" value="<%=StringUtils.trimToEmpty(user.getUserEmail()) %>" maxlength="20" class="">
								</div>
							</div>
						</div>
						
						<div class="span4">
							<ul class="thumbnails">
								<li class="span10">
									<div class="thumbnail">
										<img id="userPic" src="<%=path %>/images/260x180.gif" alt="" style="width:260px;height: 180px;">
										<input type="hidden" name="userPicture" id="user_picture" value=""/>
										<div class="caption">
											<h5>
												照片信息
											</h5>
											<div class="btn-group">
												<a id="upload_pic_btn" href="#" class="btn btn-primary">上传</a>
											</div>
										</div>
									</div>
								</li>
							</ul>
						</div>
						
					</div>
					<div class="span12">
						<div class=" form-actions">
						    <%
						    	if(edit){
						    %>
						    	<input type="submit" name="update" value="保存用户" class="btn btn-primary"">
						    <%		
						    	}else{
							%>
								<input type="submit" name="create" value="保存用户" class="btn btn-primary" />
							<%							    		
						    	}
						    %>
							<input type="button" name="return" value="返回" class="btn" onclick="window.location.href='index.jsp'" />
						</div>
					</div>
				</fieldset>
			</form>

		<div id="menuContent" class="menuContent" style="display:none; position: absolute;background-color: #EEE;">
			<ul id="branchTree" class="ztree" style="margin-top:0; width:210px;border: 1px solid #DDD; "></ul>
		</div>

		</div>
		<script src="<%= path %>/scripts/bootstrap.js"></script>
		<script src="<%= path %>/scripts/jquery.uploadify.js"></script>
		<script src="<%= path %>/scripts/jquery.validate.js"></script>
		<script src="<%= path %>/scripts/global.js"></script>
		<script src="<%= path %>/scripts/jquery.ztree.js"></script>
		<script>

		var zNodes =[
					<%
					List<Branch> branchs = BranchManager.getInstance().getBranchs();
					int i = 0;
					int k = branchs.size();
					for(Branch branch : branchs){
						i++;
						String data = "{id:"+branch.getBrId()+", name: '"+branch.getBrName()+"' ";
						if(branch.getBrParentId()!=null){
							data +=",pId:"+branch.getBrParentId()+"";
						}
						data +="}";
						if(i!=k){
							data +=",";
						}
						out.println(data);
					}
					%>		     		
			];
			var setting = {
				view: {
					dblClickExpand: false
				},
				data: {
					simpleData: {
						enable: true
					}
				},
				callback: {
					beforeClick: beforeClick,
					onClick: onClick
				}
			};
			
			function beforeClick(treeId, treeNode) {}
			
			function onClick(e, treeId, treeNode) {
				var zTree = $.fn.zTree.getZTreeObj("branchTree"),
				nodes = zTree.getSelectedNodes(),
				v = "";
				k = "";
				nodes.sort(function compare(a,b){return a.id-b.id;});
				for (var i=0, l=nodes.length; i<l; i++) {
					v += nodes[i].name + ",";
					k += nodes[i].id + ",";
				}
				if (v.length > 0 ) v = v.substring(0, v.length-1);
				if (k.length > 0 ) k = k.substring(0, k.length-1);
				var brNameObj = $("#brName");
				brNameObj.attr("value", v);
				var brIdObj = $("#brId");
				brIdObj.attr("value", k);
				$("#menuContent").fadeOut("fast");
			}

			function hideMenu() {
				$("#menuContent").fadeOut("fast");
				$("body").unbind("mousedown", onBodyDown);
			}
			function onBodyDown(event) {
				if (!(event.target.id == "menuContent" || $(event.target).parents("#menuContent").length>0)) {
					hideMenu();
				}
			}
			function showMenu() {
				var cityObj = $("#brName");
				var cityOffset = $("#brName").offset();
				$("#menuContent").css({left:cityOffset.left + "px", top:cityOffset.top + cityObj.outerHeight() + "px"}).slideDown("fast");
				$("body").bind("mousedown", onBodyDown);
			}	
		   $().ready(function() {
				$("#upload_pic_btn").uploadify({
					fileTypeExts : '*.gif; *.jpg; *.png',
				    formData      : {'reName' : 'true','uploadDir':'userpic'},
					height		  : 30,
					buttonImage   : '<%=path%>/images/browse-btn.png',
					swf			  : '<%=path%>/scripts/uploadify.swf',
					uploader:     '<%=path%>/ajaxFileUpload',
					width	      : 120,
			        onUploadSuccess : function(file, data, response) {
					    $("#userPic").attr("src",'<%=path%>/'+data); 
					    $("#user_picture").val('<%=path%>/'+data); 
					}
				});
			
				$("#userForm").validate({
					rules: {
					    brName: {
							required:true
						},
						loginNo: {
							required:true,
							minlength:2
						},
						userName: {
							required:true,
							minlength:2
						},
						userType: {
							required:true
						},
						userStatus: {
							required:true
						}
					},
					
					messages: {
					}
				});	

				$.fn.zTree.init($("#branchTree"), setting, zNodes);
						
			});
		</script>
		
	</body>